#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("Client");
    socket = new QTcpSocket(this);
    ui->le_ip->setText("127.0.0.1");
    ui->le_port->setText("8080");

    connect(socket, &QTcpSocket::readyRead, this, &Widget::readMessage);

    connect(socket,&QTcpSocket::disconnected, this, [=](){
        ui->lb_conn->setText("断开连接");
    });
    connect(socket, &QTcpSocket::connected, this,[=](){
        ui->lb_conn->setText("已连接");
    });
}

Widget::~Widget()
{
    delete ui;
}

void Widget::readMessage()
{
    QString message=socket->readAll();
    DataList.push_back(message);
    ui->le_receive->setText(message);
}


void Widget::on_bt_conn_clicked()
{
    socket->connectToHost(ui->le_ip->text(),
                          ui->le_port->text().toInt());
}

void Widget::on_bt_disconn_clicked()
{
    socket->disconnectFromHost();
}

void Widget::on_bt_send_clicked()
{

    QString str = ui->le_send->text();
    socket->write(str.toUtf8());
}

void Widget::on_bt_all_clicked()
{
    QString str;
    for (auto mess:DataList){
        str += mess + '\n';
    }
    QMessageBox::information(nullptr, "信息", str);
}

void Widget::on_bt_clear_clicked()
{
    DataList.clear();
    QMessageBox::information(nullptr, "信息", "已清空");
}
